package com.jmu.bishe.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;



/**
 *<pre><b><font color="blue">ConversionUtil</font></b></pre>
 *
 *<pre><b>&nbsp;--转换工具--</b></pre>
 * <pre></pre>
 * <pre>
 * <b>--样例--</b>
 *   ConversionUtil obj = new ConversionUtil();
 *   obj.method();
 * </pre>
 * JDK版本：JDK1.5
 */
public class ConversionUtil {
	
	private static Map<Class, Map<String,String>> classFiledsMap = new HashMap<Class, Map<String,String>>();
	
	public static final int TYPE_NORMAL_KEY = 0;
	public static final int TYPE_LOWER_KEY = 1;
	public static final int TYPE_UPPER_KEY = 2;
	
	public static Map<String, Object> getMapFromObject(Object obj, Class<?> clazz, int type){
		Map<String, Object> resMap = new HashMap<String, Object>();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field:fields){
			String fieldName = field.getName();
			String key = null;
			switch (type) {
			case TYPE_NORMAL_KEY:
				key = fieldName;
				break;
			case TYPE_LOWER_KEY:
				key = fieldName.toLowerCase();
				break;
			case TYPE_UPPER_KEY:
				key = fieldName.toUpperCase();
				break;
			}
			if(key == null){
				return null;
			}
			Object object = ReflectionUtils.getFieldValue(obj, fieldName);
			//String value = StringUtils.getObjectToString(ReflectionUtils.getFieldValue(obj, fieldName));
			resMap.put(key, object);
		}
		return resMap;
	}
	
	public static Map<String, Object> getNormalMapFromObject(Object obj, Class<?> clazz){
		return getMapFromObject(obj, clazz, TYPE_NORMAL_KEY);
	}
	
	public static Object getObjectFromMap(Map<?,?> map, Class<?> clazz){
		Object obj = null;
		try {
			obj = clazz.newInstance();
			Field[] fields = clazz.getDeclaredFields();
			Map<String, String> m = null;
			if(classFiledsMap.containsKey(clazz)){
				m = classFiledsMap.get(clazz);
			}else{
				m = new HashMap<String, String>();
				for(Field field:fields){
					String fieldName = field.getName();
					m.put(fieldName.toUpperCase(), fieldName);
				}
				classFiledsMap.put(clazz, m);
			}
			if(map != null){
				for(Entry<?,?> entry:map.entrySet()){
					String key = StringUtils.getObjectToString(entry.getKey());
					Object value = entry.getValue();//自己定制
					
					String fieldName = m.get(key.toUpperCase());
					if(fieldName != null && value != null){
						ReflectionUtils.setFieldValue(obj, fieldName, value);
					}
				}
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
